<template>
  <a-modal :open="props.modelVisible" title="课程管理" destroyOnClose @cancel="handleCancel" width="610px">
    <template #footer>
      <div style="display: flex; justify-content: center;">
        <a-button 
          type="primary" 
          danger 
          style="margin:0 10px;" 
          @click="showDeleteConfirm"
        >删除</a-button>
        <a-button 
          style="margin:0 10px;" 
          @click="editOrSubmit"
        >{{ disabled ? '编辑' : '提交' }}</a-button>
        <a-button 
          type="primary" 
          @click="handleOk" 
          style="margin:0 10px;"
        >确认</a-button>
      </div>
    </template>
    
    <a-form 
      ref="formRef" 
      :model="formState" 
      :label-col="{ style: { width: '130px' } }" 
      :wrapper-col="{ span: 14 }" 
      :disabled="disabled" 
      :rules="rules"
    >
      <a-form-item label="课程名称" name="courseName">
        <a-input v-model:value="formState.courseName" />
      </a-form-item>
      
      <a-form-item label="课程描述" name="courseDescription">
        <a-textarea 
          v-model:value="formState.courseDescription" 
          :autoSize="{ minRows: 4, maxRows: 4 }" 
          allowClear 
        />
      </a-form-item>
      
      <a-form-item label="课程状态" name="courseStatus">
        <a-select ref="select" v-model:value="formState.courseStatus">
          <a-select-option :value="0">未开课</a-select-option>
          <a-select-option :value="1">进行中</a-select-option>
          <a-select-option :value="2">已结课</a-select-option>
        </a-select>
      </a-form-item>
      
      <a-form-item label="开始时间" name="startTime">
        <a-date-picker v-model:value="formState.startTime" style="width: 100%;" show-time />
      </a-form-item>
      
      <a-form-item label="结束时间" name="endTime">
        <a-date-picker v-model:value="formState.endTime" style="width: 100%;" show-time />
      </a-form-item>
    </a-form>
    
    <a-divider style="margin: 10px 0"></a-divider>
    
    <div>
      <div style="margin-bottom: 10px;">
        <span style="font-weight: bold;">课程管理选项</span>
      </div>
      <a-space>
        <a-button type="primary" @click="navigateToMemberManagement">
          <template #icon><TeamOutlined /></template>
          人员管理
        </a-button>
        <a-button type="primary" @click="navigateToTaskManagement">
          <template #icon><ProfileOutlined /></template>
          任务管理
        </a-button>
        <a-button type="primary" @click="navigateToGradeManagement">
          <template #icon><BarChartOutlined /></template>
          成绩管理
        </a-button>
      </a-space>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import dayjs from 'dayjs';
import CourseDao from '@/daos/course_dao';
import type { Rule } from 'ant-design-vue/es/form';
import { message, Modal } from 'ant-design-vue';
import { useRouter } from 'vue-router';
import { 
  TeamOutlined, 
  ProfileOutlined, 
  BarChartOutlined, 
  ExclamationCircleOutlined 
} from '@ant-design/icons-vue';
import { h } from 'vue';

const courseDao = new CourseDao();
const formRef = ref();
const disabled = ref(true);
const router = useRouter();

interface Course {
  courseId: number;
  courseName: string;
  courseDescription?: string;
  description?: string;  // 可能存在的描述字段
  courseStatus: number;
  startTime?: dayjs.Dayjs;
  endTime?: dayjs.Dayjs;
  course_startTime?: string | dayjs.Dayjs;  // 可能的日期字段
  course_endTime?: string | dayjs.Dayjs;    // 可能的日期字段
  course_type?: string;  // 课程类型
  periods?: string;      // 课时
  college?: string;      // 学院
  [key: string]: any;    // 允许其他可能的字段
}

const formState = reactive<Course>({
  courseId: undefined,
  courseName: undefined,
  courseDescription: undefined,
  courseStatus: undefined,
  startTime: undefined,
  endTime: undefined
});

const props = defineProps({
  modelVisible: {
    type: Boolean,
    default: false
  },
  course: {
    type: Object as () => Course,
    default: null
  }
});

const emit = defineEmits(['update:modelVisible', 'confirm']);

// 编辑/提交切换
const editOrSubmit = () => {
  disabled.value = !disabled.value;

  if (disabled.value) {
    formRef.value
      .validateFields()
      .then(async () => {
        try {
          // 创建提交的课程数据对象
          const submitData: Record<string, any> = {
            course_name: formState.courseName,
            course_description: formState.courseDescription,
            course_type: props.course?.course_type || "1", // 保留原有课程类型
            periods: props.course?.periods || "0", // 保留原有课时
            college: props.course?.college || "1", // 保留原有学院
          };
          
          if (formState.startTime) {
            const startTimeStr = dayjs(formState.startTime).format('YYYY-MM-DD HH:mm:ss');
            submitData.course_startTime = startTimeStr;
          }
          
          if (formState.endTime) {
            const endTimeStr = dayjs(formState.endTime).format('YYYY-MM-DD HH:mm:ss');
            submitData.course_endTime = endTimeStr;
          }
          
          // 更新课程
          const result = await courseDao.updateCourse({
            courseData: JSON.stringify(submitData),
            courseId: formState.courseId
          });
          
          // 更新课程状态
          await courseDao.updateCourseStatus(formState.courseId, formState.courseStatus);
          
          message.success('课程信息更新成功');
          emit('confirm');
        } catch (error) {
          console.error('更新课程信息失败:', error);
          message.error('更新课程信息失败');
        }
      })
      .catch(info => {
        console.log('表单验证失败:', info);
      });
  }
};

// 删除课程确认
const showDeleteConfirm = () => {
  Modal.confirm({
    title: '确定要删除此课程吗?',
    icon: () => h(ExclamationCircleOutlined),
    content: '删除后将无法恢复，且相关的任务、班级、小组等数据也会被删除',
    okText: '确定',
    okType: 'danger',
    cancelText: '取消',
    async onOk() {
      try {
        const result = await courseDao.deleteCourse(formState.courseId);
        if (result.data.code === 200) {
          message.success('删除课程成功');
          // 删除后返回课程列表
          router.push({ name: 'CourseListView' });
        } else {
          message.error(result.data.msg || '删除课程失败');
        }
      } catch (error) {
        console.error('删除课程错误:', error);
        message.error('删除课程失败: ' + (error.message || '未知错误'));
      }
    }
  });
};

// 导航到课程人员管理页面
const navigateToMemberManagement = () => {
  router.push({
    name: '课程详情-人员管理',
    params: { courseId: formState.courseId }
  });
  emit('update:modelVisible', false);
};

// 导航到课程任务管理页面
const navigateToTaskManagement = () => {
  router.push({
    name: '课程详情-任务管理',
    params: { courseId: formState.courseId }
  });
  emit('update:modelVisible', false);
};

// 导航到课程成绩管理页面
const navigateToGradeManagement = () => {
  router.push({
    name: '课程详情-成绩管理',
    params: { courseId: formState.courseId }
  });
  emit('update:modelVisible', false);
};

// 更新表单数据
const updateFormState = () => {
  if (props.course) {
    formState.courseId = props.course.courseId;
    formState.courseName = props.course.courseName;
    formState.courseDescription = props.course.courseDescription || props.course.description;
    formState.courseStatus = props.course.courseStatus || 0;
    
    if (props.course.startTime) {
      formState.startTime = dayjs(props.course.startTime);
    } else if (props.course.course_startTime) {
      formState.startTime = dayjs(props.course.course_startTime);
    }
    
    if (props.course.endTime) {
      formState.endTime = dayjs(props.course.endTime);
    } else if (props.course.course_endTime) {
      formState.endTime = dayjs(props.course.course_endTime);
    }
    
    disabled.value = true;
  }
};

// 监听模态框打开状态
watch(
  () => props.modelVisible,
  (newValue) => {
    if (newValue && props.course) {
      updateFormState();
    }
  }
);

// 监听课程数据变化
watch(
  () => props.course,
  (newValue) => {
    if (newValue && props.modelVisible) {
      updateFormState();
    }
  }
);

// 初始化时如果已有数据则更新表单
onMounted(() => {
  if (props.course) {
    updateFormState();
  }
});

const handleCancel = () => {
  emit('update:modelVisible', false);
};

const handleOk = () => {
  emit('update:modelVisible', false);
};

// 表单验证规则
const rules: Record<string, Rule[]> = {
  courseName: [
    { required: true, message: '课程名称不能为空', trigger: 'blur' },
  ],
  courseStatus: [
    { required: true, message: '课程状态不能为空', trigger: 'blur' },
  ]
};
</script>

<style scoped>
.ant-form-item {
  margin-bottom: 16px;
}
</style> 